package com.lc.context;

import com.lc.config.annos.Exclude;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;

/**
 * @author liuc
 * @date 2021/4/18
 * @description
 **/
@Exclude
public class PkgParser {
    private List<String> resolvedClzNames;
    private String pkg;
    public PkgParser(String pkg){
        this.pkg = pkg;
        resolvedClzNames = new ArrayList<>();
        parse(pkg);
    }

    private void parse(String pkg){
        String originPkg = pkg;
        //包名
        Enumeration<URL> urls = null;
        try {
            urls = PkgParser.class.getClassLoader().getResources(pkg.replace(".", "/"));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("parse package " + pkg +" fail!");
        }
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            if ("file".equals(url.getProtocol())) {
                String realPath = url.getFile();
                File file = new File(realPath);
                if (file.exists()) {
                    if(file.isDirectory()){
                        File[] files = file.listFiles();
                        if(files == null || files.length == 0){
                            continue;
                        }
                        for (File f : files) {
                            if(f.isDirectory()){
                                parse(pkg+"."+f.getName());
                            }else{
                                String className = (originPkg+"."+f.getName()).replace(".class","");
                                resolvedClzNames.add(className);
                            }
                        }
                    }else{
                        resolvedClzNames.add((originPkg+"."+file.getName()).replace(".class",""));
                    }
                }
            }
        }
    }

    public List<String> results(){
        String[] c = Arrays.copyOf(this.resolvedClzNames.toArray(new String[this.resolvedClzNames.size()]),this.resolvedClzNames.size());
        return Arrays.asList(c);
    }
}
